//
//  BookingAddController.m
//  whopaidforit
//
//  Created by Hoang Vu on 1/26/13.
//  Copyright (c) 2013 Hoang Vu. All rights reserved.
//

#import "BookingAddController.h"
#define FORMAT_DATE @"dd-MM-yyyy"
#define ROUND_NUM @"€ %.02f"

@interface BookingAddController ()

@end

@implementation BookingAddController

@synthesize txtAmount, txtDate, txtPaid, btPaid, txtTitle, iconPaid, viewParent, viewBooking, scrollView, keyboardToolbar;

@synthesize arrayPersons,paidUserPicker,datePicker, lbCurrency, symbol, paidId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.arrayPersons = [[NSMutableArray alloc] init];
    [self createNavigation];
    [self loadData];
    [self changeStyle];
    [self showGripUser];
    [self createPopup];
    [self hideDatePicker];
}

-(void) createNavigation
{
    Event *event = [Event instance];
    UIButton *left =[UIButton buttonWithType:UIButtonTypeCustom];
    UIButton *right =[UIButton buttonWithType:UIButtonTypeCustom];
    [left setImage:[UIImage imageNamed:@"buttonlist"] forState:UIControlStateNormal];
    left.frame = CGRectMake(8, 8, 37, 35);
    right.frame = CGRectMake(250, 8, 60, 35);
    [right setTitle:@"Gereed" forState:UIControlStateNormal];
    NSString *title = event._name;
    [left addTarget:self action:@selector(openBookingList) forControlEvents:UIControlEventTouchUpInside];
    [right addTarget:self action:@selector(saveBooking) forControlEvents:UIControlEventTouchUpInside];
    [StyleControl naviStyle:self.view andTitle:title andColor:0 andleftButton:left andRightButton:right borderLeft:1 borderRight:1];
}
-(void) loadData
{
    Helper *helper = [Helper instance];
    Event *event = [Event instance];
    User *user = [User instance];
    self.arrayPersons = [user getMemberByEventWS:event._id];
    symbol = [helper showSymbol:event.currency];
    lbCurrency.text = symbol;
    paidId = 0;
}

-(void) changeStyle
{
    [StyleControl background:self.view];
    [StyleControl setViewStyle:self.viewBooking];
    [StyleControl drawLine:self.viewBooking PositionX:0 PositionY:40 Width:310];
    [StyleControl drawLine:self.viewBooking PositionX:0 PositionY:80 Width:310];
    [StyleControl drawLine:self.viewBooking PositionX:0 PositionY:120 Width:310];
    [StyleControl drawLine:self.viewBooking PositionX:0 PositionY:180 Width:310];
    [StyleControl setDateStyleTextField:txtDate];
    [StyleControl setPriceStyle:lbCurrency];
    lbCurrency.textColor = [UIColor colorWithRed:63/255.0f green:134/255.0f blue:196/255.0f alpha:1];
    [StyleControl setPriceStyleTextField:txtAmount];
}

-(void)showGripUser
{
    [self.scrollView setShowsVerticalScrollIndicator:NO];
    //scroll view
    for(UIView *subview in [self.scrollView subviews]) {
        [subview removeFromSuperview];
        //NSLog(@"Subviews Count=%d",myScrollView.subviews.count);
    }
    //number items per row
    int a=3;
    //number items per column
    int b=2;
    //total items + 1 for add item in last
    int c=[self.arrayPersons count];
    //width of scrollView
    int d=scrollView.frame.size.width;
    //height of scrollView
    int d2=scrollView.frame.size.height;
    //width of an item
    int e=d/a;
    //height of an item
    int f=d2/b-10;
    int i=0;
    int numPages = ceil(1.0f*c/(a*b));
    for (int p=0; p<numPages; p++) {
        for (int m=0; m<b; m++) {
            for (int n=0; n<a && i<c; n++) {
                UIView *itemView = [[UIView alloc] initWithFrame:CGRectMake(((p*d)+(n*e)), (m*f), e, f)];
                if(m==1 && n==0){
                    UIView *lineGray = [[UIView alloc] initWithFrame:CGRectMake(5, -3, 290, 2)];
                    lineGray.backgroundColor = [UIColor colorWithRed:224/255.0f green:224/255.0f blue:224/255.0f alpha:224/255.0f];
                    [itemView addSubview:lineGray];
                    [lineGray release];
                }
                ParticipateClass  *par = [self.arrayPersons objectAtIndex:i];
                //define padding
                int p = 10;
                UITapGestureRecognizer *singleFingerTap =
                [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
                //create rightline
                if(n<2){
                    UIView *lineGray = [[UIView alloc] initWithFrame:CGRectMake(e+7-p, p, 2, f-(p*2))];
                    lineGray.backgroundColor = [UIColor colorWithRed:224/255.0f green:224/255.0f blue:224/255.0f alpha:224/255.0f];
                    [itemView addSubview:lineGray];
                    [lineGray release];
                }
                
                //create itemprice
                UILabel *itemPrice = [[UILabel alloc] initWithFrame:CGRectMake(0, p, e-10-p, 20)];
                itemPrice.tag = 2000+i;
                [StyleControl setLabelStyle:itemPrice andText:[NSString stringWithFormat:@"%@ %.2f",symbol, par.price] andTextAlignment:@"right" andFont:[UIFont fontWithName:@"Century Gothic" size:19] andTextColor:[UIColor colorWithRed:15/255.0f green:131/255.0f blue:231/255.0f alpha:1] andBackgroundColor:nil andShadowColor:nil andShadowOffset:CGSizeMake(0, 0)];
                [StyleControl setPriceStyle:itemPrice];
                itemPrice.minimumFontSize = 5;
                itemPrice.adjustsFontSizeToFitWidth = YES;
                [itemView addSubview:itemPrice];
                [itemPrice release];
                
                //create itemperson
                UILabel *itemPerson = [[UILabel alloc] initWithFrame:CGRectMake(0, p+20, e-10-p, 20)];
                
                [StyleControl setLabelStyle:itemPerson andText:par.name andTextAlignment:@"right" andFont:[UIFont systemFontOfSize:13] andTextColor:[UIColor grayColor] andBackgroundColor:nil andShadowColor:nil andShadowOffset:CGSizeMake(0, 0)];
                
                itemPerson.userInteractionEnabled = YES;
                //itemPerson.tag = 1000+i;
                itemPerson.tag = par.quantity;
                [itemPerson addGestureRecognizer:singleFingerTap];
                
                [itemView addSubview:itemPerson];
                [itemPerson release];
                
                CPPickerView *itemCountPerson = [[CPPickerView alloc] initWithFrame:CGRectMake(0, p+42, e-p, 30)];
                itemCountPerson.backgroundColor = [UIColor clearColor];
                itemCountPerson.dataSource = self;
                itemCountPerson.delegate = self;
                itemCountPerson.tag = 3000+i;
                itemCountPerson.itemFont = [UIFont systemFontOfSize:15];
                itemCountPerson.itemColor = [UIColor grayColor];
                itemCountPerson.peekInset = UIEdgeInsetsMake(-10, 0, 0, 0);
                
                itemCountPerson.selectedItem = par.quantity;
                //[itemCountPerson reloadData];
                [itemView addSubview:itemCountPerson];
                
                //create smallavatar
                UIImageView *smallAvatarView = [[UIImageView alloc] initWithFrame:CGRectMake(e-25-p, p+45, 16, 16)];
                smallAvatarView.image = [UIImage imageNamed:@"icons1"];
                [smallAvatarView setAlpha:0.5];
                [itemView addSubview:smallAvatarView];
                [smallAvatarView release];
                
                UIImageView *swipeAvatarView = [[UIImageView alloc] initWithFrame:CGRectMake(e-60-p, p+65, 50, 16)];
                swipeAvatarView.image = [UIImage imageNamed:@"swipe"];
                [swipeAvatarView setAlpha:0.5];
                [itemView addSubview:swipeAvatarView];
                [swipeAvatarView release];
                
                [singleFingerTap release];
                
                [scrollView addSubview:itemView];
                [itemView release];
                i++;
            }
        }
    }
    scrollView.contentSize = CGSizeMake(d*(numPages), d2);
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
}

-(void) openBookingList
{
    BookingListController *detail = [[BookingListController alloc] init];
    [self presentViewController:detail animated:YES completion:NULL];
    [detail release];
}
-(void) saveBooking
{
    if(self.paidId == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Boekingen"
                                                        message:@"Sleep gebruiker die deze rekening betaalt naar het 'Betaald door' vlak."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }else {
        //save data
        ParticipateClass *par = [[ParticipateClass alloc] init];
        NSMutableArray *temp = [[NSMutableArray alloc] init];
        for (int i=0; i<self.arrayPersons.count; i++) {
            CPPickerView *itemCountPerson = (CPPickerView*)[self.view viewWithTag:3000+i];
            //par = [[ParticipateClass alloc] init];
            par = [self.arrayPersons objectAtIndex:i];
            par.quantity = itemCountPerson.selectedItem;
            [temp addObject:par];
        }
        self.arrayPersons = temp;
        NSMutableString * result = [[NSMutableString alloc] init];
        int first = 1;
        for(int i=0;i<[arrayPersons count];i++){
            par = [arrayPersons objectAtIndex:i];
            if(par.quantity){ // have quantity
                if(first){
                    [result appendString:[NSString stringWithFormat:@"%d,%d",par.userId, par.quantity] ];
                    first = 0;
                }else {
                    [result appendString:[NSString stringWithFormat:@"-%d,%d",par.userId, par.quantity]];
                }
            }
        }
        [par release];
        User *user = [User instance];
        Event *event = [Event instance];
        Entry *entry = [Entry instance];
        entry._id = [entry addEntryWS:user._id Amount:txtAmount.text Description:txtTitle.text DateExpenses:txtDate.text eventId:event._id paidFor:self.paidId ParticipantStr:result];
        [self openBookingList];
    }
}
-(IBAction)showPaidUser:(id)sender
{
    [self showDatePicker:1];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    // Any additional checks to ensure you have the correct textField here.
    [textField resignFirstResponder];
    return YES;
}
-(void) createPopup{
    UIView *pickerView = [[UIView alloc] initWithFrame:CGRectMake(60, 183, 200, 150)];
    UIToolbar *datePickerTimerToolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 200, 40)] autorelease];
    datePickerTimerToolbar.barStyle=UIBarStyleBlackTranslucent;
    
    NSArray *barPickerTimerItems = [NSArray arrayWithObjects:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease], [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(hideDatePicker)] autorelease], nil];
    
    [datePickerTimerToolbar setItems:barPickerTimerItems animated:YES];
    //[pickerView addSubview:self.paidUserPicker];
    [pickerView addSubview:datePickerTimerToolbar];
    [self.view addSubview:pickerView];
    [pickerView setHidden:YES];
    paidUserPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 200, 110)];
	
	paidUserPicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
	//CGSize pickerSize = [myPickerView sizeThatFits:CGSizeZero];
	paidUserPicker.frame = CGRectMake(0, 40, 200, 162);
    
	paidUserPicker.showsSelectionIndicator = YES;	// note this is default to NO
	
    // this view controller is the data source and delegate
	paidUserPicker.delegate = self;
	paidUserPicker.dataSource = self;
	
	// add this picker to our view controller, initially hidden
    paidUserPicker.hidden = NO;
	[pickerView addSubview:paidUserPicker];
    
    // ===============
    // // DatePicker
    // ===============
    UIView *datePickerView = [[UIView alloc] initWithFrame:CGRectMake(20, 100, 300, 200)];
    UIToolbar *datePickerToolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 300, 44)] autorelease];
    datePickerToolbar.barStyle=UIBarStyleBlackTranslucent;
    
    //[datePickerToolbar sizeToFit];
    NSArray *barPickerItems = [NSArray arrayWithObjects:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease], [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(hideDatePicker)] autorelease], nil];
    
    [datePickerToolbar setItems:barPickerItems animated:YES];
    
    self.datePicker = [[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 250, 156)] autorelease];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    [self.datePicker addTarget:self action:@selector(datePickerValueChanged) forControlEvents:UIControlEventValueChanged];
    [datePickerView addSubview:self.datePicker];
    [datePickerView addSubview:datePickerToolbar];
    [self.view addSubview:datePickerView];
    //[datePickerToolbar release];
    //[datePickerView setHidden:NO];
    
    #pragma -mark define toolbar for keyboard
    self.keyboardToolbar = [[[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)] autorelease];
    self.keyboardToolbar.barStyle=UIBarStyleBlackTranslucent;
    [self.keyboardToolbar sizeToFit];
    
    NSArray *barItems = [NSArray arrayWithObjects:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease], [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(hideKeyBoardByButton)] autorelease], nil];
    
    [self.keyboardToolbar setItems:barItems animated:YES];
}
- (CGRect)pickerFrameWithSize:(CGSize)size
{
	CGRect screenRect = [[UIScreen mainScreen] applicationFrame];
	CGRect pickerRect = CGRectMake(	0.0,
                                   screenRect.size.height - 42.0 - size.height,
                                   size.width,
                                   size.height);
	return pickerRect;
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    //show for keyboard
    [self hideDatePicker];
    if (textField == self.txtDate) {
        [self showDatePicker:0];
        return NO;
    }else if(textField == self.txtPaid){
        [self showDatePicker:1];
        return NO;
    }else if(textField == self.txtAmount){
        [textField setInputAccessoryView:self.keyboardToolbar];
        //return NO;
    }
    return YES;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    if (textField == self.txtAmount) {
        [self reloadMoney];
    }
    return YES;
}
- (void)hideKeyBoardByButton {
    [self textFieldShouldReturn:txtAmount];
    [self hideDatePicker];
}
-(void) datePickerValueChanged {
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:FORMAT_DATE];
    self.txtDate.text = [df stringFromDate:self.datePicker.date];
    //[df release];
}
-(void)hideDatePicker
{
    [self.txtTitle resignFirstResponder];
    //[self.datePicker setHidden:YES];
    [self.datePicker.superview setHidden:YES];
    //[self.paidUserPicker setHidden:YES];
    [self.paidUserPicker.superview setHidden:YES];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == txtAmount) {
        NSNumberFormatter *formatter = [NSNumberFormatter new];
        [formatter setNumberStyle: NSNumberFormatterCurrencyStyle];
        NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"nl_NL"] autorelease];
        [formatter setLocale:locale];
        [formatter setCurrencySymbol:@""];
        [formatter setLenient:YES];
        [formatter setGeneratesDecimalNumbers:YES];
        NSString *replaced = [textField.text stringByReplacingCharactersInRange:range withString:string];
        NSDecimalNumber *amount = (NSDecimalNumber*) [formatter numberFromString:replaced];
        
        if (amount == nil) {
            // Something screwed up the parsing. Probably an alpha character.
            return NO;
        }
        
        // If the field is empty (the inital case) the number should be shifted to
        // start in the right most decimal place.
        short powerOf10 = 0;
        if ([textField.text isEqualToString:@""]) {
            powerOf10 = -formatter.maximumFractionDigits;
        }
        // If the edit point is to the right of the decimal point we need to do
        // some shifting.
        else if (range.location + formatter.maximumFractionDigits >= textField.text.length) {
            // If there's a range of text selected, it'll delete part of the number
            // so shift it back to the right.
            if (range.length) {
                powerOf10 = -range.length;
            }
            // Otherwise they're adding this many characters so shift left.
            else {
                powerOf10 = [string length];
            }
        }
        amount = [amount decimalNumberByMultiplyingByPowerOf10:powerOf10];
        
        // Replace the value and then cancel this change.
        textField.text = [[formatter stringFromNumber:amount] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        [formatter release];
        return NO;
    } else {
        return YES;
    }
}
-(void)showDatePicker:(NSInteger) value
{
    if(value==0){
        //[self.datePicker setHidden:NO];
        [self.datePicker.superview setHidden:NO];
        //[self.paidUserPicker setHidden:YES];
        [self.paidUserPicker.superview setHidden:YES];
        [self datePickerValueChanged];
    }else{
        //[self.datePicker setHidden:YES];
        [self.datePicker.superview setHidden:YES];
        //[self.paidUserPicker setHidden:NO];
        [self.paidUserPicker.superview setHidden:NO];
        [self pickerView:self.paidUserPicker didSelectRow:0 inComponent:0];
    }
    
}

#pragma mark - CPPickerViewDataSource
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	NSString *returnStr = @"";
	ParticipateClass *par = [arrayPersons objectAtIndex:row];
    returnStr = par.name;
	
    return returnStr;
}
- (NSInteger)numberOfItemsInPickerView:(CPPickerView *)pickerView
{
    return 11;
}
- (NSString *)pickerView:(CPPickerView *)pickerView titleForItem:(NSInteger)item
{
    return [NSString stringWithFormat:@"%i x", item];
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return [arrayPersons count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}
- (void)pickerView:(CPPickerView *)pickerView didSelectItem:(NSInteger)item{
    [self reloadMoney];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	if([arrayPersons count]){
        ParticipateClass *par = [arrayPersons objectAtIndex:[pickerView selectedRowInComponent:0]];
        self.txtPaid.text = [NSString stringWithFormat:@"Betaald door %@",par.name];
        self.paidId = par.userId;
        NSLog(@"image %@", par.image);
        [btPaid setImage:[Helper getImageMember:par ] forState:UIControlStateNormal];
	}
}
- (void)reloadMoney {
    Helper *helper = [Helper instance];
    double a = [[helper moneyToString:self.txtAmount.text] doubleValue];
    float totalPersons = 0;
    for (int i=0; i<self.arrayPersons.count; i++) {
        CPPickerView *itemCountPerson = (CPPickerView*)[self.view viewWithTag:3000+i];
        totalPersons = totalPersons + itemCountPerson.selectedItem;
    }
    float b = a/totalPersons;
    for (int i=0; i<self.arrayPersons.count; i++) {
        CPPickerView *itemCountPerson = (CPPickerView*)[self.view viewWithTag:3000+i];
        UILabel *itemPrice = (UILabel*)[self.view viewWithTag:2000+i];
        itemPrice.text = [StyleControl formatCurrency:[NSString stringWithFormat:@"%@ %.02f",symbol, b*(itemCountPerson.selectedItem)] addCurency:YES];
    }
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
